<?php
class Settings_model extends MY_Model
{
	public
		$table = 'settings',
		$prKey = 'name'
	;
	
	function __construct()
	{
		parent::__construct();
		
		$this->fields = array(
			'name'  => T_('Parameter'),
			'value' => T_('Value'),
			'uom' 	=> T_('Unit of Measure'),
			'description' => T_('Description'),
		);
		
		$this->rules = array(
			'name'  => "trim|strip_tags|required|max_length[255]|callback___nameUnique",
			'value' => "trim|strip_tags|required|max_length[255]",
			'uom' => "trim|strip_tags|max_length[64]",
			'description' => "trim|strip_tags|max_length[1000]",
		);		
	}
	
	function get($option = '')
	{
		$sql = "SELECT * FROM ".$this->table;
		$order_by = " ORDER BY id DESC";
		
		if ($option)
		{
			$sql .= " WHERE name=".$this->db->escape($option);
			$sql .= $order_by;
			return $this->db->query($sql)->row();
		}
		else
		{
			$sql .= $order_by;
			
			return $this->db->query($sql)->result();
		}
	}
	
	function set_settings($option, $value)
	{				
		$this->db->where('name', $option);						
		return $this->db->update($this->table, array('value' => $value));
	}
	
	function delete($items_serialized = null)
	{
		$items = explode("&", $items_serialized);
		
		$report = "";
		foreach ($items as $id)
		{	
			$data = $this->settings_model->get($id);
			
			$res = $this->db->delete($this->table, array($this->prKey => $id));	
			
			if (is_null($res))
			{
				$this->log->writeMessage('error', T_('Error. Parameter was not deleted.'));
				$report .= ",0"; // don't deleted
			}
			else
			{
				$this->log->writeMessage('done', T_('Parameter was deleted.'));
				$report .= ",1"; // deleted				
			}
		}
		
		return substr($report, 1);
	}
		
	function insert($data)
	{
		if (!empty($data))
		{			
			parent::insert($data);

			if ($this->db->insert_id() > 0)
			{
				$this->log->writeMessage('done', T_('Parameter added succesfully.'));
				
				return TRUE;
			}
			else
			{
				$this->log->writeMessage('error', T_('Error! Parameter was not created.'));
				
				return FALSE;
			}
		}		
	}

	function update($data)
	{
		if (!empty($data))
		{
			$sql = 'UPDATE '.$this->table.' SET name='.$this->db->escape($data['name']).', value='.$this->db->escape($data['value']).', uom='.$this->db->escape($data['uom']).', description='.$this->db->escape($data['description']).' WHERE name='.$this->db->escape($this->parameter);
			$res = $this->db->query($sql);

			$this->log->writeMessage('done', T_('Saved succesfully.'));

			return TRUE;			
		}		
	}	
	
	function nameUnique($name = null)
	{
		$this->db->where('name', $name);
    
		if(!empty($this->id_parameter))
		{
			$this->db->where('id !=', $this->id_parameter); 
		}
    
    	$query = $this->db->get($this->table);

    	if (!$query->num_rows())
    	{
      		return TRUE;
    	}   
    
		return FALSE;
	}
  
}
?>